package com.trainingcloud.action.document;

import java.util.Vector;

import org.dom4j.Element;

import com.trainingcloud.XMLSerializer;
import com.trainingcloud.action.BaseSessionAction;
import com.trainingcloud.dao.DocumentDAO;
import com.trainingcloud.dao.FavoriteDAO;
import com.trainingcloud.dao.HistoryDAO;
import com.trainingcloud.entity.ClientDocument;
import com.trainingcloud.entity.Document;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public class ListDocumentAction extends BaseSessionAction 
{
	private String type;
	private int count;
	private int documentId;
	
	public ListDocumentAction() throws SystemException 
	{
		super();
	}

	@Override
	public String callWithSession() throws DAOException, SystemException 
	{
		Vector<ClientDocument> result = null;
		DocumentDAO documentDAO = new DocumentDAO();		
		
		if(type.compareTo("one")==0)
		{
			result = new Vector<ClientDocument>();
			Document document = documentDAO.getDocumentById(documentId);
			ClientDocument clientDocument = new ClientDocument();
			clientDocument.setDocument(document);
			FavoriteDAO favoriteDAO = new FavoriteDAO();
			clientDocument.setFavorite(favoriteDAO.isFavorited(this.currentUser.getId(), documentId));
			HistoryDAO historyDAO = new HistoryDAO();
			clientDocument.setLatestUsedTime(historyDAO.getLatestUsedTime(this.currentUser.getId(), documentId));
			result.add(clientDocument);
		}
		else if(type.compareTo("mine")==0)
		{
			result = documentDAO.getAllDocumentsByOwner(currentUser.getId());
		}
		else if(type.compareTo("favorited")==0)
		{
			result = documentDAO.getFavoriteDocuments(currentUser.getId());
		}
		else if(type.compareTo("latestUsed")==0)
		{
			result = documentDAO.getLatestUsedDocuments(currentUser.getId(), count);
		}
		else if(type.compareTo("shared")==0)
		{
			result = documentDAO.getAllSharedDocuments(currentUser.getId());
		}
		else
		{
			return "Invalid type.";
		}
		
		Element listElement = responseElement.addElement("documentList");
		for(int i=1; i<=result.size(); i++)
		{
			XMLSerializer.clientDocumentToXML(result.get(i-1), listElement);
		}
		
		return null;
	}

	public String getType() 
	{
		return type;
	}

	public void setType(String type) 
	{
		this.type = type;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public int getDocumentId() {
		return documentId;
	}

	public void setDocumentId(int documentId) {
		this.documentId = documentId;
	}

}
